<template>
  <view>
    <view class="address-add-wrap" >
      <view class="split-black"></view>
      <view class="cell">
        <skeleton row="1" :loading="loading">
          <view class="cell__li">
            <view class="cell__li--label">联系人</view>
            <input
              :value="receiverName"
              @input="inputValue($event, 'receiverName')"
              class="cell__li--input"
              type="text"
              placeholder-style="color: #ABABAB"
              placeholder="请填写联系人姓名"
            />
          </view>
        </skeleton>
        <skeleton row="1" :loading="loading">
          <view class="cell__li">
            <view class="cell__li--label">手机号码</view>
            <input
              :value="mobile"
              @input="inputValue($event, 'mobile')"
              class="cell__li--input"
              type="number"
              placeholder-style="color: #ABABAB"
              placeholder="请填写收货人手机号"
            />
          </view>
        </skeleton>
        <skeleton row="1" :loading="loading">
          <view class="cell__li" >
            <view class="cell__li--label">所在小区</view>
            <areaSelect :defaultValue="defaultValue" @change="chooseArea" />
          </view>
        </skeleton>
        <skeleton row="2" :loading="loading">
          <view class="cell__li address-detail">
            <view class="cell__li--label">详细地址</view>
            <view class="cell__li--textarea">
              <textarea
                disable-default-padding="true"
                :value="address"
                @input="inputValue($event, 'address')"
                class="cell__li--textarea-input"
                placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元室等"
                placeholder-style="color: #ABABAB"
              />
            </view>
          </view>
        </skeleton>
        <view
          :style="{
            background: '#F5F5F5',
            height: '20rpx',
            transform: 'translateX(-40rpx)',
            width: '750rpx',
          }"
        />
        <skeleton row="1" :loading="loading">
          <view class="cell__li default-li">
            <view class="cell__li--default">
              <view class="cell__li--default-title">设置为默认地址</view>
              <view class="cell__li--default-desc">提醒：每次下单会默认推荐使用该地址</view>
            </view>
            <u-switch v-model="isDefault" />
          </view>
        </skeleton>
      </view>

      <!-- 操作区 -->
      <view class="save">
        <button
          class="pp-button save__btn"
          :class="[active ? 'on' : '']"
          hover-class="pp-button--active"
          @tap="handleSave"
        >
          保存
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import uSwitch from '@/basic-components/u-switch/index.vue';
import Skeleton from '@/basic-components/u-skeleton/index.vue';
import areaSelect from '@/components/area-select.vue';
import { NullString, CheckPhone } from '@/tool/index';
import {
  ADD_RECEIVER,
  RECEIVER_EDIT,
  RECEIVER_INFO,
  USER_GET_AREA_BY_NAME,
} from '@/api/user';

export default {
  components: {
    uSwitch,
    Skeleton,
    areaSelect
  },
  data() {
    return {
      receiverId: '', // 地址id
      receiverName: '',
      mobile: '',
      defaultValue: [], // 默认值
      provinceId: 0,
      province: '',
      cityId: 0,
      city: '',
      district: '',
      districtId: 0,
      town: 0,
      town_name: '',
      village: 0,
      village_name: '',
      address: '',
      isDefault: false,
      community:'',
      community_name:'',
      loading: true,
      // 地址联动
      areaShow: false,
    };
  },
  computed: {
    active() {
      // 可点击
      if (NullString(this.receiverName)) {
        return false;
      }
      if (NullString(this.mobile)) {
        return false;
      }
      if (!this.provinceId) {
        return false;
      }
      if (NullString(this.address)) {
        return false;
      }

      return true;
    },
  },
  async onLoad(option) {
    console.log("add address");
    const { id } = option;

    if (id) {
      // 编辑
      uni.setNavigationBarTitle({
        title: '编辑收货地址',
      });
      this.receiverId = id;
      // 详情
      await this.getAddressDetail(id);
    } else {
      this.loading = false;
      uni.setNavigationBarTitle({
        title: '添加收货地址',
      });
    }
  },
  methods: {
    inputValue(event, name) {
      // 赋值
      const { value } = event.detail;
      this[name] = value;
    },
    chooseArea(data) {
      // 地区选择
      console.log('data------',data);
      data.map((item)=>{
        if(item.level===1){
          this.province = item.name;
          this.provinceId = item.regions_code;
        }else if(item.level===2){
          this.city = item.name
          this.cityId = item.regions_code;
        }else if(item.level===3){
          this.district = item.name;
          this.districtId = item.regions_code;
        }else if(item.level===4){
          this.town_name = item.name;
          this.town = item.regions_code;
        }
        else if(item.level===5){
          this.village_name = item.name;
          this.village = item.regions_code;
          this.community_name = item.name;
          this.community = item.regions_code;
        }
        // else if(item.level===5){
        //   this.community_name = item.name;
        //   this.community = item.regions_code;
        // }

      });
    },
    async getAddressDetail(id) {
      // 地址详情
      const res = await this.$http.get(RECEIVER_INFO +'/' + id);
      const data = res.data;
      const areaList = data.region.split(' ');

      this.receiverName = data.delivery_name;
      this.mobile = data.mobile;
      this.province = data.province_name || areaList[0];
      this.provinceId = data.province;
      this.city = data.city_name || areaList[1];
      this.cityId = data.city;
      this.district = data.district_name || areaList[2] || '';
      this.districtId = data.district;

      this.town =  data.town;
      this.town_name = data.town_name || areaList[3] || '';
      this.village = data.village;
      this.village_name = data.village_name || areaList[4] || '';

      this.address = data.address;
      this.isDefault = !!data.is_default;

      await this.getRegionByName(this.village_name);

      this.loading = false;
    },
    getRegionByName(name){
      this.$http.get(USER_GET_AREA_BY_NAME, {
            name: name,
          })
          .then((res) => {
            this.defaultValue = [res.data[0].id];
          })
    },
    /* eslint-disable */
    isEmojiCharacter(substring) {
      // 表情符判断
      for (let i = 0; i < substring.length; i++) {
        const hs = substring.charCodeAt(i);
        if (hs >= 0xd800 && hs <= 0xdbff) {
          if (substring.length > 1) {
            var ls = substring.charCodeAt(i + 1);
            const uc = (hs - 0xd800) * 0x400 + (ls - 0xdc00) + 0x10000;
            if (uc >= 0x1d000 && uc <= 0x1f77f) {
              return true;
            }
          }
        } else if (substring.length > 1) {
          var ls = substring.charCodeAt(i + 1);
          if (ls == 0x20e3) {
            return true;
          }
        } else {
          if (hs >= 0x2100 && hs <= 0x27ff) {
            return true;
          }
          if (hs >= 0x2b05 && hs <= 0x2b07) {
            return true;
          }
          if (hs >= 0x2934 && hs <= 0x2935) {
            return true;
          }
          if (hs >= 0x3297 && hs <= 0x3299) {
            return true;
          }
          if (
            hs == 0xa9 ||
            hs == 0xae ||
            hs == 0x303d ||
            hs == 0x3030 ||
            hs == 0x2b55 ||
            hs == 0x2b1c ||
            hs == 0x2b1b ||
            hs == 0x2b50
          ) {
            return true;
          }
        }
      }
    },
    /* eslint-disable */
    handleSave() {
      // 保存
      if (NullString(this.receiverName)) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none',
        });
        return;
      }
      if (!this.community_name || this.community_name==='请选择') {
        uni.showToast({
          title: '请选择所在地区(精确第五级)',
          icon: 'none',
        });
        return;
      }
      if (NullString(this.mobile)) {
        uni.showToast({
          title: '请输入收货人手机号',
          icon: 'none',
        });
        return;
      }
      if (!CheckPhone(this.mobile)) {
        uni.showToast({
          title: '手机号格式错误',
          icon: 'none',
        });
        return;
      }
      if (NullString(this.address)) {
        uni.showToast({
          title: '请输入详细地址',
          icon: 'none',
        });
        return;
      }

      // 表情字符屏蔽
      if (this.isEmojiCharacter(this.address.trim())) {
        uni.showToast({
          title: '详细地址不能含有表情符',
          icon: 'none',
        });
        return;
      }


      if (!this.receiverId) {
        // 添加地址
        this.saveAddressAjax();
      } else {
        // 编辑地址
        this.saveEditAddressAjax();
      }
    },
    saveAddressAjax() {
      const addReceiverRequest = {
        delivery_name: this.receiverName,
        mobile: this.mobile,
        province: this.provinceId,
        province_name: this.province,
        city: this.cityId,
        city_name: this.city,
        district: this.districtId,
        district_name: this.district,
        town: this.town,
        town_name: this.town_name,
        village: this.village,
        village_name: this.village_name,
        address: this.address,
        is_default:  this.isDefault ? 1 : 0,
        region: `${this.province} ${this.city} ${this.district} ${this.town_name} ${this.village_name}`,
      };

      this.$http
        .post(ADD_RECEIVER, addReceiverRequest, {
          showLoading: true,
        })
        .then(() => {
          uni.hideLoading();
          uni.showToast({
            icon: 'none',
            mask: true,
            title: '添加成功',
            duration: 1000,
          });

          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
        });
    },
    saveEditAddressAjax() {
      // 编辑地址
      const addReceiverRequest = {
        id: this.receiverId,
        delivery_name: this.receiverName,
        mobile: this.mobile,
        province: this.provinceId,
        province_name: this.province,
        city: this.cityId,
        city_name: this.city,
        district: this.districtId,
        district_name: this.district,
        town: this.town,
        town_name: this.town_name,
        village: this.village,
        village_name: this.village_name,
        community:this.community,
        community_name:this.community_name,
        address: this.address,
        is_default:  this.isDefault ? 1 : 0,
        region: `${this.province} ${this.city} ${this.district} ${this.town_name} ${this.village_name}`,
      };
      this.$http
        .put(RECEIVER_EDIT, addReceiverRequest, {
          showLoading: true,
        })
        .then(() => {
          uni.hideLoading();
          uni.showToast({
            icon: 'none',
            mask: true,
            title: '编辑成功',
            duration: 1000,
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
        });
    },
  },
};
</script>

<style lang="less">
.address-add-wrap {
  position: relative;
  min-height: 100vh;
  padding-bottom: 160rpx;
  padding-bottom: calc(160rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(160rpx + env(safe-area-inset-bottom));
  background-color: #ffffff;

  .split-black {
    width: 100%;
    height: 20rpx;
    background-color: #f5f5f5;
  }

  .cell {
    padding-left: 40rpx;

    &__li {
      display: flex;
      align-items: center;
      padding: 46rpx 20rpx 44rpx 0;
      border-bottom: 1px solid #eeeeee;

      &.default-li {
        justify-content: space-between;
      }

      &.address-detail {
        align-items: flex-start;
      }

      &--label {
        flex-shrink: 0;
        width: 170rpx;
        font-size: 30rpx;
        line-height: 42rpx;
        font-weight: bold;
      }

      &--input {
        flex: 1;
        display: flex;
        font-size: 30rpx;
        align-items: center;

        &-placeholder {
          font-size: 30rpx;
          color: #ababab;
        }
      }

      &--arrow {
        flex-shrink: 0;
        font-size: 44rpx;
        color: #cccccc;
      }

      &--textarea {
        height: 108rpx;
        width: 100%;
        &-input {
          width: 100%;
          height: 100%;
          font-size: 30rpx;
        }
      }

      &--default {
        &-title {
          font-size: 30rpx;
          line-height: 42rpx;
          font-weight: 500;
          margin-bottom: 8rpx;
        }

        &-desc {
          font-size: 26rpx;
          line-height: 36rpx;
          color: #494949;
        }
      }
    }

    &__address {
      padding: 36rpx 30rpx 24rpx 0;

      &-smart {
        display: flex;
        justify-content: space-between;
        margin-bottom: 28rpx;

        &-identify {
          height: 42rpx;
          font-size: 30rpx;
          font-weight: 500;
          color: #333333;
          line-height: 42rpx;
        }

        &-help {
          height: 34rpx;
          font-size: 24rpx;
          font-weight: 400;
          color: #999999;
          line-height: 34rpx;
        }
      }

      &-textarea {
        padding: 24rpx 20rpx;
        width: 636rpx;
        height: 116rpx;
        background: #f9f9f9;
        border-radius: 8rpx;
        border: 1rpx solid #ebebef;
      }

      &-select {
        display: flex;
        align-items: center;
        margin-top: 24rpx;
        height: 50rpx;

        &-picture {
          align-items: center;
          display: flex;

          .iconfont {
            font-size: 32rpx;
          }
        }

        &-voice {
          margin-left: 48rpx;
          align-items: center;
          display: flex;

          .iconfont {
            font-size: 32rpx;
          }
        }

        &-empty {
          margin-left: 114rpx;
          align-items: center;
          display: flex;

          .iconfont {
            font-size: 32rpx;
          }
        }

        &-item {
          margin-left: 10rpx;
          height: 36rpx;
          font-size: 26rpx;
          font-weight: 400;
          color: #333333;
          line-height: 36rpx;
        }

        .identify-button {
          width: 108rpx;
          height: 50rpx;
          margin-left: 18rpx;
          background: #fedd00;
          border-radius: 12rpx;
          font-size: 24rpx;
          font-weight: 500;
          color: #333333;
          line-height: 50rpx;
        }
      }
    }
  }

  .save {
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 160rpx;
    padding-bottom: 0;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);

    &__btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 670rpx;
      height: 108rpx;
      font-size: 32rpx;
      font-weight: 500;
      color: #999999;
      border-radius: 54rpx;
      background-color: #eeeeee;

      &.on {
        color: #333333;
        background-color: #fedd00;
      }
    }
  }
}
</style>
